package com.zxy.leetcode._01100_01199._01180_01189;

/**
 * https://leetcode-cn.com/problems/day-of-the-week/
 *
 * 一周中的第几天
 * 给出的日期一定是在 1971 到 2100 年之间的有效日期。
 *
 * 标签：日期
 *
 * 思路
 * java自带的Calendar
 * 距离1971.1.1的天数后取模
 * 基姆拉尔森计算公式
 */
public class Test01185 {

    public static void main(String[] args) {
        Test01185 test = new Test01185();
        System.out.println(test.dayOfTheWeek(1, 1, 1971));
        System.out.println(test.dayOfTheWeek(31, 8, 2019));
    }

    /**
     *
     * https://leetcode-cn.com/problems/day-of-the-week/solution/c-fei-mo-fa-jie-fa-by-daxianwa/
     *
     * 其他人的思路
     * 首先我们知道1971.1.1是Friday
     * 然后我们计算给定日期距离1971.1.1的天数，再取模计算即可
     */
    public String dayOfTheWeek(int day, int month, int year) {
        int[] daysOfMonth={0,31,28,31,30,31,30,31,31,30,31,30,31};
        String[] weeks = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        int days = 0;

        for (int y=1971; y<year; y++) {
            if (isLeapYear(y)) {
                days += 366;
            }else {
                day += 365;
            }
        }
        for (int m=1; m<month; m++) {
            days += daysOfMonth[m];
        }
        days += day;
        if (month > 2 && isLeapYear(year)) {
            days ++;
        }

        // 如果传入的是1971.1.1，计算结果days为1，为了得到Friday，需加上4
        days = days + 4;

        return weeks[days%7];
    }

    // 是否闰年
    private boolean isLeapYear(int y) {
        return (y%400 == 0) || (y%4 == 0 && y%100 != 0);
    }

    // 使用java自带的Calendar
    public String dayOfTheWeek2(int day, int month, int year) {
        String[] weeks = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        // 月份在java里面是减1处理的
        calendar.set(year, month-1, day);
        return weeks[calendar.get(java.util.Calendar.DAY_OF_WEEK)-1];
    }
}
